package com.sgl.config.quarz;


import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * 定时任务的注册类
 *
 *
 */
@Component
public class SchedulerAllJob{

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    public void scheduleJobs() throws SchedulerException {

        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        scheduler.clear();

        scheduleJob1(scheduler);

        scheduleJob2(scheduler);
    }

    public void scheduleJob1(Scheduler scheduler) throws SchedulerException {

        /*

         * 此处可以先通过任务名查询数据库，如果数据库中存在该任务，则按照ScheduleRefreshDatabase类中的方法，更新任务的配置以及触发器

         * 如果此时数据库中没有查询到该任务，则按照下面的步骤新建一个任务，并配置初始化的参数，并将配置存到数据库中

         */

        JobDetail jobDetail = JobBuilder.newJob(CheckCallBack.class) .withIdentity("job1", "group1").usingJobData("count",5).build();
        // 每10分钟执行一次

        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/10 * * * ?");//0 0/10 * * * ?

        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") .withSchedule(scheduleBuilder).build();

        scheduler.scheduleJob(jobDetail,cronTrigger);

    }

    private void scheduleJob2(Scheduler scheduler) throws SchedulerException{
        JobDetail jobDetail = JobBuilder.newJob(CheckOrderTimeOut.class) .withIdentity("job2", "group1").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0 0/1 * * ? ");//每小时执行一次
        // 每小时检查一次超时单子

        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger2", "group1") .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail,cronTrigger);

    }
}
